<template>
  <el-drawer v-model="drawer" size="90%">
    <template #title>
      <div class="sj-title">
        {{ dataInfo.oppo_name }}
      </div>
    </template>
    <section class="opportunity-detail">
      <!-- <h3 class="opportunity-title">
        {{ dataInfo.oppo_name }}
      </h3> -->
      <div class="opportunity-header">
        <div>
          <div class="header-label">关联客户</div>
          <div class="header-content">
            {{ dataInfo.customer_name }}
          </div>
        </div>
        <div>
          <div class="header-label">预算金额(元)</div>
          <div class="header-content">{{ dataInfo.business_budget }}</div>
        </div>
        <div>
          <div class="header-label">负责销售</div>
          <div class="header-content">{{ dataInfo.owner_name }}</div>
        </div>
        <div>
          <div class="header-label">创建时间</div>
          <div class="header-content">{{ dataInfo.created_at }}</div>
        </div>
        <div>
          <div class="header-label">更新时间</div>
          <div class="header-content">{{ dataInfo.updated_at }}</div>
        </div>
      </div>
      <div class="opportunity-steps">
        <el-steps process-status="finish" :space="200" :active="active" simple>
          <el-step :title="item.name" v-for="(item, i) in scheduleOptions" @click="stepFun(item, i)" />
        </el-steps>
        <div v-if="dataInfo.status !== 3 && dataInfo.status !== 6">
          <el-select style="width: 150px" class="search-top-select" v-model="stepData" placeholder="结果设置">
            <el-option label="失败" :value="3" />
            <el-option label="赢单" :value="6" />
          </el-select>
          <el-button style="margin: 10px" type="primary" @click="submitStep">提交</el-button>
        </div>
      </div>
      <section class="opportunity-content">
        <div class="content-left">
          <div style="margin-top: 20px">
            <h4>商机信息</h4>
            <el-descriptions border :column="2" style="margin-top: 10px">
              <el-descriptions-item label="商机性质">{{ dataInfo.business_nature }}
              </el-descriptions-item>
              <el-descriptions-item label="项目把握度">{{
                dataInfo.possibility
              }}</el-descriptions-item>
              <el-descriptions-item label="规划时间">{{
                dataInfo.plan_time
              }}</el-descriptions-item>
              <el-descriptions-item label="招标时间">
                {{ dataInfo.bidding_time }}
              </el-descriptions-item>
              <el-descriptions-item label="商机所在地">
                {{ dataInfo.province }}
                {{ dataInfo.city }}
                {{ dataInfo.area }}
              </el-descriptions-item>
              <el-descriptions-item label="建设缘由">
                {{ dataInfo.business_cause }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div style="margin-top: 30px">
            <div class="content-title">
              <h4>关联产品</h4>
              <el-button type="primary" size="small" @click="addGoods">+ 添加</el-button>
            </div>
            <el-table border stripe :data="goodsTable">
              <el-table-column label="商品名称" width="500">
                <template #default="{ row }">
                  <div class="manage-info">
                    <el-image :preview-teleported="true" style="width: 50px; min-width: 50px; height: 50px"
                      :src="row.cover" :zoom-rate="1.2" :preview-src-list="[row.cover]" :initial-index="4" fit="cover"
                      class="img-box" />
                    <div class="right">
                      <span>{{ row.goods_name }} </span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="" label="规格">
                <template #default="{ row }">
                  <div v-for="item in row.items">
                    {{ item.goods_spec }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="售价(元)" prop="price_selling" />
              <el-table-column label="操作" width="90" align="center">
                <template #default="{ row }">
                  <!-- <el-button type="primary" link @click="updateFun(row)">编辑</el-button> -->
                  <el-button type="danger" link @click="delFun(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 30px">
            <div class="content-title">
              <h4>跟进记录</h4>
              <el-button type="primary" size="small" @click="addFollow">+ 添加</el-button>
            </div>
            <div v-if="logsArr.length > 0">
              <div class="logs-list-item" v-for="item in logsArr">
                <div class="left">
                  <el-image style="width: 46px; height: 46px" :src="imgSrc" :zoom-rate="1.2" fit="cover" />
                </div>
                <div class="right">
                  <div class="title right-space">
                    {{ item.contact?.name }}
                    <span v-if="item.contact?.post">
                      ({{ item.contact?.post }})
                    </span>
                    <span style="color: #e4750e; margin-left: 10px; font-size: 12px">
                      {{ item.communication }}
                    </span>
                  </div>
                  <div class="user right-space">
                    创建人:{{ item.created_user }}
                  </div>
                  <div class="time right-space">
                    <span class="time-1">
                      <!-- <img :src="icon3Png" alt="" /> -->
                      <span> 时间:{{ item.created_at }} </span>
                    </span>
                    <span class="time-2">
                      <!-- <img :src="icon4Png" alt="" /> -->
                      <span> 下次拜访时间:{{ item.next_time }} </span>
                    </span>
                  </div>
                  <!-- <div class="label right-space">
                                    <span v-if="item.opportunity_name"> #{{ item.opportunity_name }}# </span>
                                    {{ item.content }}
                                </div> -->
                  <div class="other">
                    <div class="other-item">
                      <span class="other-item-label">跟进情况</span>
                      <span class="other-item-content">
                        {{ item.content }}
                      </span>
                    </div>
                    <div class="other-item">
                      <span class="other-item-label">遇到问题</span>
                      <span class="other-item-content">
                        {{ item.question }}
                      </span>
                    </div>
                    <div class="other-item">
                      <span class="other-item-label">下步计划</span>
                      <span class="other-item-content">
                        {{ item.plan }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                <el-pagination :small="true" v-model:currentPage="followPage" v-model:page-size="followSize"
                  :page-sizes="[20, 50, 100, 200]" layout="total, prev, pager, next, jumper" :total="followTotal"
                  @size-change="followTotalSizeChange" @current-change="followTotalCurrentChange" />
              </div>
            </div>
            <div v-else class="no-data">暂无跟进记录</div>
          </div>
        </div>
        <div class="content-right">
          <div>
            <div class="content-title user-title">
              <h4>参与人员</h4>
              <el-button type="primary" size="small" @click="addUser">+ 添加</el-button>
            </div>
            <el-table border stripe :data="tableUsers">
              <el-table-column prop="username" label="姓名" />
              <el-table-column prop="postion" label="角色" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="{ row }">
                  <el-button type="primary" link @click="updateUsertFun(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" link @click="delUserFun(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 20px">
            <div class="content-title user-title">
              <h4>联系人</h4>
              <el-button type="primary" size="small" @click="addContacts">+ 添加</el-button>
            </div>
            <el-descriptions :column="1" border v-for="item in tableContacts" style="margin-bottom: 30px">
              <template #title>
                <div class="descriptions-title">
                  <div class="descriptions-title-name">
                    {{ item.contact_name }}
                  </div>
                  <div class="btn-box">
                    <el-button type="primary" link @click="updateContactFun(item)">
                      编辑
                    </el-button>
                    <el-button type="danger" link @click="delContacFun(item)">
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
              <el-descriptions-item label="职位">{{ item.contact_position }}
              </el-descriptions-item>
              <el-descriptions-item label="电话">
                {{ item.mobile }}
              </el-descriptions-item>
              <el-descriptions-item label="态度">
                {{ item.contact_manner }}
              </el-descriptions-item>
              <el-descriptions-item label="关系">
                {{ item.contact_relation }}
              </el-descriptions-item>
              <!-- <el-descriptions-item label="操作"> </el-descriptions-item> -->
            </el-descriptions>
            <div style="
                font-size: 13px;
                color: #adb1b4;
                text-align: center;
                margin: 20px 0;
              " v-if="tableContacts.length == 0" class="no-data">
              暂无联系人
            </div>
          </div>
          <div style="margin-top: 20px">
            <div class="content-title user-title">
              <h4>相关文档</h4>
              <el-button type="primary" size="small" @click="addFile">+ 添加</el-button>
            </div>
            <el-table border stripe :data="fileList">
              <el-table-column prop="" label="文件">
                <template #default="{ row }">
                  <a :href="row.url" :download="row.filename" target="_blank">
                    {{ row.filename }}
                  </a>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="url" label="文件地址">
                <template #default="{ row }">
                  <a :href="row.url" :download="row.filename" target="_blank">
                    {{ row.url }}
                  </a>
                </template>
              </el-table-column> -->

              <el-table-column label="操作" width="80" align="center">
                <template #default="{ row }">
                  <el-button type="danger" link @click="delFileFun(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
    </section>
    <!-- 添加关联商品 -->
    <goodsPage :dataInfo="dataInfo" ref="goodsPageRef" @refreshList="refreshList" />
    <!-- 跟进 -->
    <followDialog ref="followDialogRef" :dataInfo="dataInfo" @followList="followList" />
    <!-- 参与人员 -->
    <userDialog ref="userDialogRef" :dataInfo="dataInfo" @refreshUser="refreshUser" />
    <!-- 联系人 -->
    <contactsDialog ref="contactsDialogRef" :dataInfo="dataInfo" @refreshContacts="refreshContacts" />
    <!-- 相关文档 -->
    <dialogAddFile ref="dialogAddFileRef" :dataInfo="dataInfo" @refreshFile="refreshFile" />
  </el-drawer>
</template>
<script setup>
import imgSrc from "@/assets/imgs/icon/icon5.png";
// 字典查询
import { listApi as dictApi } from "@/plugins/api/system/dict";
// 进度api
import {
  selStageApi,
  finishApi,
} from "@/plugins/api/customer/manage/opportunity";
// 商品关联
import {
  listApi as opportunityApi,
  delApi,
} from "@/plugins/api/customer/manage/opportunityGoods";
// 跟进记录
import { followUpListApi } from "@/plugins/api/customer/manage/followUp";
// 参与人员
import { userListApi, userDeleteApi } from "@/plugins/api/customer/manage/user";
// 联系热人
import {
  contactsListApi,
  contactsDeleteApi,
} from "@/plugins/api/customer/manage/oppo_contacts";
// 相关文档
import { docsListApi, docsDelApi } from "@/plugins/api/customer/manage/file";
// 添加商品组件
import goodsPage from "../DialogOpportunity-goods.vue";
// 跟进组件
import followDialog from "../DialogFollow.vue";
// 参与人员组件
import userDialog from "../DialogUser.vue";
// 联系人组件
import contactsDialog from "../DialogContacts.vue";
// 相关文档
import dialogAddFile from "../DialogAddFile.vue";
//
// import icon3Png from "../../../assets/imgs/icon/icon3.png";
// import icon4Png from "../../../assets/imgs/icon/icon4.png";
//
let route = useRoute();
let router = useRouter();
// 点击商机进度
const emit = defineEmits(["refreshList"]);
let active = ref(0);
function stepFun(row, index) {
  if (dataInfo.value.status == 3 || dataInfo.value.status == 6) return;
  ElMessageBox.confirm(`确定把销售阶段设为“${row.name}”，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (active.value == index) {
        if (active.value < 1) return;
        active.value = active.value - 1;
      } else {
        active.value = index;
      }
      selStageApi({
        id: dataInfo.value.id,
        stage: row.name,
      }).then((res) => {
        ElMessage.success("操作成功！");
        dataInfo.value.project_stage = res.project_stage;
        emit("refreshList");
        // router.push({
        //   query: {
        //     oppoInfo: JSON.stringify(dataInfo.value),
        //   },
        // });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}

// 商机进度

let scheduleOptions = ref([]);
function getSchedule() {
  getDictionary(7).then((res) => {
    scheduleOptions.value = res;
    if (dataInfo.value.project_stage) {
      scheduleOptions.value.forEach((item, i) => {
        if (item.name == dataInfo.value.project_stage) {
          active.value = i;
        }
      });
    }
    if (dataInfo.value.status == 3 || dataInfo.value.status == 6) {
      scheduleOptions.value.push({
        name: dataInfo.value.status == 3 ? "失败！" : "赢单！",
      });
      active.value = 7;
    }
    emit("refreshList");
  });
}
// 获取字典项
function getDictionary(dict_id) {
  return new Promise((resolve, reject) => {
    dictApi({ dict_id: dict_id }).then((data) => {
      resolve(data);
    });
  });
}
// 商机结果设置
let stepData = ref("");
function submitStep() {
  if (stepData.value) {
    ElMessageBox.confirm(`确定提交，是否继续?`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        finishApi({
          id: dataInfo.value.id,
          status: stepData.value,
        }).then((res) => {
          ElMessage.success("操作成功！");
          scheduleOptions.value.push({
            name: res.status == 3 ? "失败！" : "赢单！",
          });
          dataInfo.value.status = res.status;
          router.push({
            query: {
              oppoInfo: JSON.stringify(dataInfo.value),
            },
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消。",
        });
      });
  }
}
// 关联商品
let goodsTable = ref([]);
function getGoods() {
  opportunityApi({
    opportunity_id: dataInfo.value.id,
  }).then((res) => {
    goodsTable.value = res;
  });
}
let goodsPageRef = ref(null);
function addGoods() {
  goodsPageRef.value.initFun();
}
function updateFun(row) {
  goodsPageRef.value.initFun(row);
}
function delFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getGoods();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
function refreshList() {
  getGoods();
}

// 跟进记录
let logsArr = ref([]);
const followPage = ref(1);
const followSize = ref(20);
const followTotal = ref(0);
const followTotalSizeChange = (val) => {
  followSize.value = val;
  getFollow();
};
const followTotalCurrentChange = (val) => {
  followPage.value = val;
  getFollow();
};
function getFollow() {
  followUpListApi({
    page: followPage.value,
    pageSize: followSize.value,
    opportunity_id: dataInfo.value.id,
  }).then((res) => {
    logsArr.value = res.list;
    followTotal.value = res.page.total;
  });
}
let followDialogRef = ref(null);
function addFollow() {
  followDialogRef.value.initFun();
}
function followList() {
  getFollow();
}
// 参与人员
let tableUsers = ref([]);
function updateUsertFun(row) {
  userDialogRef.value.initFun("update", row);
}
function delUserFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      userDeleteApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getUser();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
function getUser() {
  userListApi({
    opportunity_id: dataInfo.value.id,
  }).then((data) => {
    tableUsers.value = data;
  });
}
function refreshUser() {
  getUser();
}
let userDialogRef = ref(null);
function addUser() {
  userDialogRef.value.initFun("add");
}
// 联系人
let contactsDialogRef = ref(null);
let tableContacts = ref([]);
function refreshContacts() {
  getContacts();
}
function getContacts() {
  contactsListApi({
    opportunity_id: dataInfo.value.id,
  }).then((data) => {
    tableContacts.value = data;
  });
}
function addContacts() {
  contactsDialogRef.value.initFun("add");
}
function updateContactFun(row) {
  contactsDialogRef.value.initFun("update", row);
}
function delContacFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      contactsDeleteApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getContacts();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
// 相关文档
let dialogAddFileRef = ref(null);
let fileList = ref([]);
function addFile() {
  dialogAddFileRef.value.initFun();
}
function getFiles() {
  docsListApi({
    opportunity_id: dataInfo.value.id,
  }).then((data) => {
    fileList.value = data;
  });
}
function delFileFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      docsDelApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getFiles();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
function refreshFile() {
  getFiles();
}
let drawer = ref(false);
let dataInfo = ref({});
function initFun(data) {
  dataInfo.value = { ...data };
  goodsTable.value = [];
  logsArr.value = [];
  tableUsers.value = [];
  tableContacts.value = [];
  fileList.value = [];
  stepData.value = "";
  drawer.value = true;
  getSchedule();
  getGoods();
  getFollow();
  getUser();
  getContacts();
  getFiles();
}
defineExpose({
  initFun,
});
</script>
<style lang="scss"  >
.opportunity-detail {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .opportunity-title {
    margin: 0;
  }

  .opportunity-header {
    width: 100%;
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #aaafaf;

    >div {
      margin-right: 5%;

      .header-label {
        font-size: 12px;
        color: #aaafaf;
        margin-bottom: 5px;
      }

      .header-content {
        font-size: 12px;
        color: #367de8;
      }
    }
  }

  .opportunity-steps {
    margin: 10px 0;

    :deep(.el-step) {
      cursor: pointer;
    }
  }

  .opportunity-content {
    display: flex;
    justify-content: space-between;

    .content-left {
      width: calc(100% - 410px);
      height: calc(100vh - 220px);
      overflow: auto;
      padding-right: 10px;
      box-sizing: border-box;

      h4 {
        margin: 0;
        font-weight: 500;
        color: #5e6c84;
      }

      .content-title {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
      }

      .manage-info {
        display: flex;

        .img-box {
          align-self: center;
        }

        .right {
          margin-left: 5px;
          align-self: center;
        }
      }

      // 跟进记录
      .logs-list-item {
        width: 100%;
        display: flex;

        padding-bottom: 20px;
        border-bottom: 1px solid #f2f2f2;
        margin-bottom: 20px;

        .left {
          padding-left: 15px;
        }

        .right {
          margin-left: 15px;

          .right-space {
            margin-bottom: 8px;
          }

          .title {
            font-size: 16px;

            color: #172b4d;
          }

          .user {
            font-size: 14px;
            font-weight: 500;
            color: #5e6c84;
          }

          .time {
            .time-1 {
              font-size: 12px;

              font-weight: 500;
              color: #5e6c84;

              img,
              span {
                vertical-align: middle;
              }
            }

            .time-2 {
              margin-left: 10px;
              vertical-align: middle;
              font-size: 12px;
              font-weight: 500;
              color: #e4750e;

              img,
              span {
                vertical-align: middle;
              }
            }
          }

          .label {
            font-size: 14px;
            font-weight: 500;

            span {
              color: #005ecc !important;
            }
          }

          .other {
            .other-item {
              .other-item-label {
                font-size: 14px;
                color: #005ecc;
              }

              .other-item-content {
                margin-left: 10px;
                font-size: 14px;
                color: #909396;
              }
            }
          }
        }
      }

      .no-data {
        text-align: center;
        color: #5e6c84;
        margin: 20px;
      }
    }

    .content-right {
      width: 400px;
      height: calc(100vh - 220px);
      overflow: auto;
      padding-right: 5px;
      box-sizing: border-box;

      .content-title {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
      }

      h4 {
        margin: 0;
      }

      .user-title {
        margin-top: 0;
      }

      .descriptions-title-name {
        font-size: 14px !important;
        margin-bottom: 0;
        color: #7a7b7c;
      }

      .el-descriptions__header {
        width: 100%;
      }

      .descriptions-title {
        width: 380px;
        display: flex;
        justify-content: space-between;

        .btn-box {}
      }
    }
  }


}

.sj-title {
  font-size: 26px !important;
  color: black;
  font-weight: 600;
}
</style>
